package com.bbb.common.util;

import com.bbb.common.exception.ServiceException;
import com.bbb.pojo.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class JwtAuthUtil {
    // 使用 Keys 类生成安全的密钥
    private static final Key SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);
    // 过期时间，单位：毫秒
    private static final long EXPIRATION_TIME = 86400000;

    // 生成 JWT
    public static String generateToken(User user) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        // 其他用户信息可以继续添加到 claims 中

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(user.getName())
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SECRET_KEY, SignatureAlgorithm.HS256)
                .compact();
    }

    // 解析 JWT
    private static Claims parseToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            throw new ServiceException("解析 token 时发生异常: " + e.getMessage());
        }
    }

    // 获取当前登录的用户 id
    public static Integer getUserId() {
        String token = getTokenFromRequest();
        Claims claims = parseToken(token);
        return (Integer) claims.get("id");
    }

    // 获取当前登录用户
    public static User getUser() {
        String token = getTokenFromRequest();
        Claims claims = parseToken(token);
        User user = new User();
        user.setId((Integer) claims.get("id"));
        // 可以根据 claims 中的其他信息继续设置 user 的属性
        return user;
    }

    // 检查是否登录
    public static boolean isLogin() {
        try {
            String token = getTokenFromRequest();
            parseToken(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    // 从请求中获取 token
    private static String getTokenFromRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        String token = request.getHeader("Authorization");
        if (token == null ||!token.startsWith("Bearer ")) {
            throw new ServiceException("未提供有效的 token");
        }
        return token.substring(7);
    }

    // 验证 JWT
    public static boolean validateToken(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .parseClaimsJws(token)
                    .getBody();
            Date expiration = claims.getExpiration();
            if (expiration.before(new Date())) {
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}